#
#   home.py
#   journalismManger
#
#   Created by luoxh on 2019-07-20-17:07.
#   Copyright © 2019 luoxh. All rights reserved.
#
from mongoengine import DoesNotExist

from src.extension.exceptions import CustomException
from src.extension.redprint import Redprint
from src.extension.status import CustomStatus
from src.model.home.news import News, NewsType
from src.viewmodel.home import NewsDetailVM, NewsListVM, NewsTypeVM

home_rp = Redprint('home')


@home_rp.route('/banner')
def banner():
    return [{'url': 'https://baidu.com/meinv1', 'name': '美女1'}, ]


@home_rp.route('/news/list/<id>')
def news_list(id):
    try: news_type = NewsType.objects.get(pk=id)
    except DoesNotExist: raise CustomException(CustomStatus.ITEM_DOES_NOT_EXIST)
    try: news_list = News.objects(news_type=news_type)
    except DoesNotExist: return {'code': 200, 'data': []}
    data = [NewsListVM(news, news_type) for news in news_list]
    print(data)
    return {'code': 200, 'data': data}


@home_rp.route('/news_type/list')
def news_type_list():
    try: news_type_list = NewsType.objects()
    except DoesNotExist: raise CustomException(CustomStatus.ITEM_DOES_NOT_EXIST)
    else: return {'code': 200, 'data': [NewsTypeVM(news_type) for news_type in news_type_list]}


@home_rp.route('/news/detail/<id>')
def news_detail(id):
    try: news = News.objects.get(pk=id)
    except DoesNotExist: raise CustomException(CustomStatus.ITEM_DOES_NOT_EXIST)
    else: return {'code': 200, 'data': NewsDetailVM(news)}
